import VueStore from '@/store'
import CryptoJS from 'crypto-js'
import settings from "@/settings";

export const getToken = () => {
  return VueStore.getters['app/token']
}
export const getOauthToken = (params) => {
  for (let key in params) {
    let token = params[key]
    key = key.toLowerCase()
    switch (key) {
      case 'cmtoken':
        settings.hunterUserOrigin = 'CmPortal'
        settings.headerAuthKey = 'Cm-Authorization'
        break
      case 'h4atoken':
        settings.hunterUserOrigin = 'H4A'
        settings.headerAuthKey = 'TOKEN'
        break
      case 'eptoken':
        settings.hunterUserOrigin = 'oss'
        settings.headerAuthKey = 'Eptoken'
        break
    }
    VueStore.commit('app/SETAUTHORIZATION', token)
    global.HUNTERHOST = global.HUNTERGATEWAY || global.HUNTERHOST
    console.log('tokenChanged')
  }
}
export const getAt = () => {
  return VueStore.getters['app/accessToken']
}

export const setToken = token => {
  VueStore.commit('app/SETAUTHORIZATION', token)
}

export const setAt = token => {
  VueStore.commit('app/SETACCESSTOKEN', token)
}

export const deleteToken = () => {
  VueStore.commit('app/SETAUTHORIZATION', null)
}

export const deleteAt = () => {
  VueStore.commit('app/SETACCESSTOKEN', null)
}

export const cleanCache = () => {
  deleteToken()
  deleteAt()
  VueStore.dispatch('menu/cleanMenuFavourite')
  location.href = './'
}

/**
 * 登录加签
 * @param {*} word
 * @param {*} keyStr
 * @returns
 */
export function encrypt(word, keyStr) {
  var key = CryptoJS.enc.Utf8.parse(keyStr)
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * 将树形菜单变成一维数组
 */
export const getMenus = () => {
  let res = []
  let menus = VueStore.state.menu.menuJSON || []
  let deep = arr => {
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i]
      res.push(item)
      if (item.children && item.children.length > 0) {
        deep(item.children)
      }
    }
  }
  deep(menus)
  return res
}

/**
 *  * 运营支撑中，多页面或者chunk的多页面等（动态路由），通常只定义前缀部分。如 /form, form/1, /form/2，只定义 /form
 *  eg '/form'  则 返回 '/form'，'/form/:id'  则 返回 '/form',
 */
export const getRealPath = route => {
  let path = decodeURI(route.path)
  if (path.startsWith('chunk/') || path.startsWith('epin/')) {
    if (route.meta.chunkMuti) {
      path = path.substring(0, path.lastIndexOf('/' + route.params.id))
    }
  } else {
    let key = (route.meta && route.meta.multiKey) || 'id'
    let params = route.params || {}
    if (Object.keys(params).length > 0 && Object.hasOwnProperty.call(params, key)) {
      path = path.substring(0, path.lastIndexOf('/' + params[key]))
    }
  }
  return path
}
